#存放装饰器

from functools import wraps

import requests


from config.env import LLM
from utils.logger import log
from config.path import screenshot_path
from datetime import datetime
from requests.exceptions import HTTPError,ConnectionError,Timeout,RequestException

def UI_exception_catcher(func):
    """捕获异常并记录日志的装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        page = kwargs.get("page")
        try:
            return func(*args, **kwargs)
        except Exception as e:
            # 记录错误日志，包含函数名称和异常信息
            log.error(f"在执行 '{func.__name__}' 时捕获到异常：{e}", exc_info=True)
            # 重新抛出异常以便上层调用者处理
            log.info('1')
            if page:
                log.info('1')
                page.screenshot(path = screenshot_path + f"/{func.__name__}---{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}.png")
                log.info('1')
            raise e
    return wrapper


def logger(func):
    """记录日志的装饰器"""
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        log.debug(f"{func.__name__}执行成功")
        return result
    return wrapper


def http_exception_catcher(func):
    """用于http请求方法捕获异常的装饰器"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            # 执行原始请求方法
            response = func(*args, **kwargs)
            # 检查响应是否为成功状态码
            return response
        except ConnectionError as conn_err:
            log.error(f"连接错误: {conn_err}")
        except Timeout as timeout_err:
            log.error(f"请求超时: {timeout_err}")
        except RequestException as req_err:
            log.error(f"请求错误: {req_err}")
        # 如果发生错误，则返回 None 表示请求失败
        return None

    return wrapper









if __name__ == '__main__':
    #
    @logger
    # @UI_exception_catcher
    def tsum(a,b):
        return a+b
    tsum(1,2)
    #
    # @http_exception_catcher
    # def t_http():
    #     respond = requests.get("https://baidu.com")
    #     return respond
    # print(t_http())

